import { defineStore } from "pinia";
import { ref } from "vue";
import { getCurrentUser } from "@/api/user";
import { UserInfo } from "@/types";

// 你可以任意命名 `defineStore()` 的返回值，但最好使用 store 的名字，同时以 `use` 开头且以 `Store` 结尾。
// (比如 `useUserStore`，`useCartStore`，`useProductStore`)
// 第一个参数是你的应用中 Store 的唯一 ID。
export const useLoginUserStore = defineStore("loginUser", () => {
  const loginUser = ref<UserInfo | null>(null);
  const loading = ref<boolean>(false);
  //远程获取登录用户信息

  function $reset() {
    loginUser.value = null;
    loading.value = false;
  }
  async function fetchLoginUser(force = false) {
    if (!force && loginUser.value && !loading.value) return;
    const cachedUser = localStorage.getItem("loginUser");
    if (cachedUser && !force) {
      loginUser.value = JSON.parse(cachedUser);
      return;
    }
    loading.value = true;
    try {
      const res = await getCurrentUser();
      if (res.data.code === 200) {
        loginUser.value = res.data.data as UserInfo;
      } else {
        loginUser.value = null;
      }
    } catch (error) {
      console.error("获取用户信息失败：" + error);
      loginUser.value = null;
    } finally {
      loading.value = false;
    }
  }
  //单独设置登陆用户信息
  function setLoginUser(newLoginUser: any) {
    loginUser.value = newLoginUser;
  }

  return { loginUser, fetchLoginUser, setLoginUser, loading, $reset };
});

export const useAuthStore = defineStore("auth", {
  state: () => ({
    showLoginModal: false,
    showCreateModal: false,
  }),
  actions: {
    openLoginModal() {
      this.showLoginModal = true;
    },
    closeLoginModal() {
      this.showLoginModal = false;
    },
  },
});

export const useUserStore = defineStore("user", {
  state: () => ({
    avatarUrl: "",
    username: "",
    birth_day: "",
    sex: "",
    signature: "",
  }),
  actions: {
    setAvatar(url: string) {
      this.avatarUrl = url;
    },
    setUsername(username: string) {
      this.username = username;
    },
    setBirthday(birth_day: string) {
      this.birth_day = birth_day;
    },
    setSex(sex: string) {
      this.sex = sex;
    },
    setSignature(signature: string) {
      this.signature = signature;
    },
  },
});
